using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Windows.Storage;
using Windows.System.UserProfile;
using Windows.Foundation.Metadata;


namespace LockscreenWin10
{
    public class LockscreenApi
    {
        public static int SetLockscreenImageSync(string name)
        {
            // Console.WriteLine(name);
            var result = SetLockscreenImageAsync(name).ConfigureAwait(true);
            int ret = result.GetAwaiter().GetResult();
            return ret;
        }

        public static async Task<int> SetLockscreenImageAsync(string path)
        {
            //Console.WriteLine(path);
            try
            {
                Uri imgUri = new Uri(path);
                StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(imgUri);
                await LockScreen.SetImageFileAsync(file);
            }
            catch (Exception)
            {
                //Console.WriteLine(1);
                return 1;
            }
            //Console.WriteLine("ok1");
            return 0;
        }

        public static async Task<int> SetLockscreenImage(string path)
        {
            var dirPath = Path.GetDirectoryName(path);
            var fileName = Path.GetFileName(path);
            Console.WriteLine(path);
            try
            {
                var folder = await StorageFolder.GetFolderFromPathAsync(dirPath);
                var imgFile = await folder.GetFileAsync(fileName);
                using (var stream = await imgFile.OpenAsync(FileAccessMode.Read))
                {
                    await LockScreen.SetImageStreamAsync(stream);
                }
            }
            catch (Exception)
            {
                //Console.WriteLine(1);
                return 1;
            }
            //Console.WriteLine("ok");
            return 0;
        }
        //async Task<bool> SetWallpaperAsync(string localAppDataFileName)
        //{
        //    bool success = false;
        //    if (UserProfilePersonalizationSettings.IsSupported())
        //    {
        //        var uri = new Uri("ms-appx:///Local/" + localAppDataFileName);
        //        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
        //        UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
        //        success = await profileSettings.TrySetLockScreenImageAsync(file);
        //    }
        //    return success;
        //}

    }
    
}
